package com.xyy.ebattery.tcp.start.runner;

import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @Description TODO
 * @Author JIA BOYAN
 * Date 2025/6/16 12:58
 */
@Slf4j
@Component
public class DataSourceRunner implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        try (
                Connection connection = dataSource.getConnection();
        ) {
            log.info("DataSource connection={}",connection);
        }
    }

    /**
     * 每2秒执行一次
     */
   // @Scheduled(cron = "0/5 * * * * ? ")
    public void printMetrics(){
        if(dataSource instanceof HikariDataSource){
            HikariPoolMXBean hikariPoolMXBean = ((HikariDataSource)dataSource).getHikariPoolMXBean();
            if(hikariPoolMXBean==null){
                log.warn("HikariPoolMXBean is null");
                return;
            }
            int totalConnections = hikariPoolMXBean.getTotalConnections();
            int activeConnections = hikariPoolMXBean.getActiveConnections();
            int idleConnections = hikariPoolMXBean.getIdleConnections();
            int threadsAwaitingConnection = hikariPoolMXBean.getThreadsAwaitingConnection();
            log.info("Hikari totalConnections={} activeConnections={} idleConnections={} threadsAwaitingConnection={}",
                    totalConnections,activeConnections,idleConnections,threadsAwaitingConnection);

        }
    }
}
